import json
from pathlib import Path
from typing import Dict, List, Any, Optional

class FileHandler:
    def __init__(self):
        self.base_path = Path(__file__).parent.parent.parent
        self.data_path = self.base_path / 'data'
        self.user_data_path = self.data_path / 'user_data'
        self.word_banks_path = self.data_path / 'word_banks'
        
        # 确保必要的目录存在
        self.user_data_path.mkdir(parents=True, exist_ok=True)
        self.word_banks_path.mkdir(parents=True, exist_ok=True)
    
    def load_word_list(self, file_path: str) -> List[str]:
        """加载词库文件"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return [line.strip() for line in f if line.strip()]
        except (FileNotFoundError, IOError):
            return []
    
    def load_json(self, filename: str) -> Optional[Dict[str, Any]]:
        """加载JSON文件"""
        file_path = self.user_data_path / filename
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            return None
    
    def save_json(self, filename: str, data: Dict[str, Any]):
        """保存JSON文件"""
        file_path = self.user_data_path / filename
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=4, ensure_ascii=False)
